package com.mpdbailey.cleverdicandroid;

import java.util.ArrayList;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.pigdogbay.androidutils.mvp.BackgroundColorPresenter;
import com.pigdogbay.androidutils.mvp.IBackgroundColorView;
import com.pigdogbay.androidutils.usercontrols.GoProNagBox;
import com.pigdogbay.androidutils.utils.ActivityUtils;

public class MainActivity extends FragmentActivity implements OnClickListener,
		OnEditorActionListener, IAnagramView, IBackgroundColorView,
		IApplicationView, OnSharedPreferenceChangeListener,GoProNagBox.IGoProResult {

	private static final String MAIN_MENU_CATEGORY = "Main Menu";

	private static final String EVENT_CATEGORY = "Search";

	EditText editQuery;
	ApplicationPresenter _ApplicationPresenter;
	BackgroundColorPresenter _BackgroundColorPresenter;
	AnagramPresenter _AnagramPresenter;
	ResultsFragment _ResultsFragment;
	HintsFragment _HintsFragment;
	Button _btnSearch;
	private ArrayList<String> matchesArray;
	private ArrayAdapter<String> itemAdapter;
	private AppData _AppData;
	private AdView _AdView;
	private GoProNagBox _GoProNagBox;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		wireUpControls();
		setupAds();

		_AppData = new AppData(this);
		_AnagramPresenter = new AnagramPresenter(this);
		_AnagramPresenter.SetFindSubAngrams(_AppData.showSubAnagrams());
		_AnagramPresenter.SetResultLimit(_AppData.getResultsLimit());
		_ApplicationPresenter = new ApplicationPresenter(this, _AppData);
		_ApplicationPresenter.setAnagramPresenter(_AnagramPresenter);
		_BackgroundColorPresenter = new BackgroundColorPresenter(this,
				_AppData.createBackgroundColorModel());
		_BackgroundColorPresenter.updateBackground();
		_ApplicationPresenter.initialize();
		PreferenceManager.getDefaultSharedPreferences(this)
				.registerOnSharedPreferenceChangeListener(this);
		
		_GoProNagBox = new GoProNagBox(this);
		_GoProNagBox.setFrequency(50)
		.setResultListener(this)
		.setUrlId(R.string.market_cleverdic_pro);
		//Get tracker - hopefully will auto track the activities
		((CleverDicApplication) getApplication()).getTracker();
		
	}

	private void wireUpControls() {
		_btnSearch = (Button) findViewById(R.id.btnSearch);
		_btnSearch.setOnClickListener(this);
		editQuery = (EditText) findViewById(R.id.editQuery);
		editQuery.setOnEditorActionListener(this);
		_HintsFragment = new HintsFragment();
		_ResultsFragment = new ResultsFragment();
		ReplaceFragment(_HintsFragment);
		matchesArray = new ArrayList<String>();
		itemAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, matchesArray);
		_ResultsFragment.setListAdapter(itemAdapter);

	}

	private void setupAds() {
		// Look up the AdView as a resource and load a request.
		_AdView = (AdView) this.findViewById(R.id.adView);
		if (_AdView != null) {
			AdRequest adRequest = new AdRequest.Builder()
					.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
					.addTestDevice(getString(R.string.code_test_device_1_id))
					.addTestDevice(getString(R.string.code_test_device_2_id))
					.addTestDevice(getString(R.string.code_test_device_3_id))
					.addTestDevice(getString(R.string.code_test_device_4_id))
					.build();
			_AdView.loadAd(adRequest);
		}
	}

	private void ReplaceFragment(Fragment fragment) {
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();
		fragmentTransaction.replace(R.id.fragmentHolder, fragment);
		fragmentTransaction.commit();
	}

	@Override
	public void onPause() {
		if (_AdView != null) {
			_AdView.pause();
		}
		super.onPause();
		_ApplicationPresenter.pause();
    	_GoProNagBox.save();
	}

	@Override
	public void onResume() {
		super.onResume();
		if (_AdView != null) {
			_AdView.resume();
		}
		_ApplicationPresenter.resume();
	}

	@Override
	protected void onDestroy() {
		if (_AdView != null) {
			_AdView.destroy();
		}
		super.onDestroy();
		try {
			PreferenceManager.getDefaultSharedPreferences(this)
					.unregisterOnSharedPreferenceChangeListener(this);
		} catch (Exception e) {
		}
	}
	@Override
	protected void onStart() {
		super.onStart();
		//Report the start of an Activity, so that it can be tracked by any Trackers that have enabled auto activity tracking
		GoogleAnalytics.getInstance(this).reportActivityStart(this);
	}
	@Override
	protected void onStop() {
		super.onStop();
		GoogleAnalytics.getInstance(this).reportActivityStop(this);;
	}
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;
		switch (item.getItemId()) {
		case (R.id.menu_clear):
			_AnagramPresenter.Clear();
			ActivityUtils.showKeyboard(this, editQuery);
			if (!_AnagramPresenter._Searching)
			{
				ReplaceFragment(_HintsFragment);
			}
			CleverDicApplication.trackEvent(this, MAIN_MENU_CATEGORY, "clear");
			break;
		case (R.id.menu_about):
			intent = new Intent(this, AboutActivity.class);
			startActivity(intent);
			break;
		case (R.id.menu_help):
			intent = new Intent(this, HelpActivity.class);
			startActivity(intent);
			break;
		case (R.id.menu_settings):
			intent = new Intent(this, SettingsActivity.class);
			startActivity(intent);
			break;
		case (R.id.menu_share):
			shareResults();
			CleverDicApplication.trackEvent(this, MAIN_MENU_CATEGORY, "share");
			break;
		case (R.id.menu_go_pro):
			ActivityUtils.ShowAppOnMarketPlace(this, R.string.market_cleverdic_pro);
			CleverDicApplication.trackEvent(this,"Main Menu","go pro");		
			break;
		default:
			return false;
		}
		return true;
	}

	public void onClick(View v) {
		ReplaceFragment(_ResultsFragment);
		_ApplicationPresenter.searchButtonPressed();
		ActivityUtils.hideKeyboard(this, editQuery.getWindowToken());
		_GoProNagBox.check();
	}

	public void setStatus(String status, boolean busy) {
		_ResultsFragment.setStatus(status, busy);
	}

	public String getQuery() {
		return this.editQuery.getText().toString();
	}

	public void setQuery(String query) {
		this.editQuery.setText(query);
	}

	public void setError(String msg) {
		editQuery.setError(msg);
	}

	public void addMatch(String match) {
		matchesArray.add(match);
		itemAdapter.notifyDataSetChanged();
	}

	public void clearMatches() {
		matchesArray.clear();
		itemAdapter.notifyDataSetChanged();
	}

	public String getStringResource(int id) {
		return getString(id);
	}

	public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
		if (arg1 == EditorInfo.IME_ACTION_DONE) {
			onClick(null);
		}
		return false;
	}

	public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
		if (key.equals(getString(R.string.code_pref_use_large_dictionary_key))) {
			_ApplicationPresenter.useLargeDictionarySettingChanged();
		} else if (key
				.equals(getString(R.string.settings_show_subanagrams_pref_key))) {
			this._AnagramPresenter
					.SetFindSubAngrams(_AppData.showSubAnagrams());
		} else if (key
				.equals(getString(R.string.settings_result_limit_pref_key))) {
			this._AnagramPresenter.SetResultLimit(_AppData.getResultsLimit());
		} else if (key.equals(getString(R.string.code_pref_background_colour))) {
			_BackgroundColorPresenter.updateBackground();
		}
	}

	private void shareResults() {
		try {
			StringBuilder sbuff = new StringBuilder();
			sbuff.append("CleverDic Query:\n");
			sbuff.append(getQuery());
			sbuff.append("\n\nMatches:\n");
			for (String result : matchesArray) {
				sbuff.append(result);
				sbuff.append('\n');
			}
			sbuff.append('\n');
			sbuff.append(getString(R.string.website));
			ActivityUtils.shareText(this, "CleverDic", sbuff.toString(),
					R.string.share_chooser_title);
		} catch (Exception e) {
			Toast.makeText(this, "Unable to share", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void showWelcomeScreen() {
		ActivityUtils.showInfoDialog(this, R.string.welcome_title,
				R.string.welcome_msg);
	}

	@Override
	public void showLoadingDictionary() {
		_btnSearch
				.setText(MainActivity.this.getString(R.string.button_loading));
		_btnSearch.setEnabled(false);
	}

	@Override
	public void showReady() {
		int textId = _ApplicationPresenter.getSearchButtonTextId();
		_btnSearch.setText(MainActivity.this.getString(textId));
		_btnSearch.setEnabled(true);
	}

	@Override
	public void showLoadingDictionaryError() {
		setError(getString(R.string.DictionaryLoadError));
	}

	@Override
	public void checkAppRate() {
		new com.pigdogbay.androidutils.apprate.AppRate(this)
				.setMinDaysUntilPrompt(7).setMinLaunchesUntilPrompt(5).init();
	}

	@Override
	public void setBackgroundColor(int id) {
		ActivityUtils.setBackground(this, R.id.rootLayout, id);
	}
	@Override
	public void trackQuery(String queryType) {
		CleverDicApplication.trackEvent(this, EVENT_CATEGORY, queryType);
	}

	@Override
	public void noGoPro() {
		CleverDicApplication.trackEvent(this, GoProNagBox.TAG, "No");
	}
	@Override
	public void yesGoPro() {
		CleverDicApplication.trackEvent(this, GoProNagBox.TAG, "Yes");
	}
}
